package net.gz01.wallet.web.controller.merch;

import static net.gz01.wallet.web.config.FDDConfig.APP_ID;
import static net.gz01.wallet.web.config.FDDConfig.APP_SECRET;
import static net.gz01.wallet.web.config.FDDConfig.HOST;
import static net.gz01.wallet.web.config.FDDConfig.V;
import static net.gz01.wallet.web.config.FDDConfig.fdd_V;
import static net.gz01.wallet.web.config.FDDConfig.fdd_hetong_url;
import static net.gz01.wallet.web.config.FDDConfig.fdd_return_url_sign;
import static net.gz01.wallet.web.config.FDDConfig.fddhost_url;
import static net.gz01.wallet.web.config.FDDConfig.getSixNum;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.codec.binary.Base64;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import net.gz01.wallet.web.controller.api.sdk.client.FddClientBase;
import net.gz01.wallet.web.controller.api.sdk.client.authForfadada.ApplyCert;
import net.gz01.wallet.web.controller.api.sdk.client.authForfadada.GetCompanyVerifyUrl;
import net.gz01.wallet.web.controller.api.sdk.client.authForfadada.GetPersonVerifyUrl;
import net.gz01.wallet.web.controller.api.sdk.client.authForfadada.model.AgentInfoINO;
import net.gz01.wallet.web.controller.api.sdk.client.authForfadada.model.BankInfoINO;
import net.gz01.wallet.web.controller.api.sdk.client.authForfadada.model.CompanyInfoINO;
import net.gz01.wallet.web.controller.api.sdk.client.authForfadada.model.LegalInfoINO;
import net.gz01.wallet.web.controller.api.sdk.client.request.ExtsignReq;
import com.jfinal.aop.Clear;

import lombok.extern.slf4j.Slf4j;
import net.gz01.util.ZOMD5;
import net.gz01.wallet.common.ZOIDGenerate;
import net.gz01.wallet.web.auth.Authority;
import net.gz01.wallet.web.config.FDDConfig;
import net.gz01.wallet.web.controller.BaseController;
import net.gz01.wallet.web.interceptors.AuthInterceptor;
import net.gz01.wallet.web.model.Account;
import net.gz01.wallet.web.model.Contacts;
import net.gz01.wallet.web.model.Merch;
import net.gz01.wallet.web.model.MerchRole;
import net.gz01.wallet.web.model.MerchUser;
import net.gz01.wallet.web.model.Org;

@Slf4j
@Clear
public class MainController extends BaseController{

	public void loginpage(){
		render("login.html");
	}

	public void home(){
		MerchUser merchUser = (MerchUser) getSession().getAttribute("loginMerchUser");
		Merch merch = Merch.dao.selectByMerchCode(merchUser.getMerchCode());
		Org org = Org.dao.selectByOrgCode(merch.getOrgCode());
		List<Contacts> cardList = Contacts.dao.find("select * from bank_card where merchCode='" +
				merch.getCode() + "'");

		Account account = Account.dao.select(merch.getCode());
		String showAmt = account.getBalanceShow();
		setAttr("balance", showAmt);
		setAttr("cardList", cardList);
		setAttr("merch", merch);
		setAttr("org", org);

		if(merch.getIsVerify() && merch.getIsSign()) {//实名认证和合同签署完成了
			render("console.html");
		}else if(!merch.getIsVerify()){
			render("verifySign.html");
		}else{
			render("signNet.html");
		}
	}

	public void login(){
		if(!validateCaptcha("vercode")){
			renderMsg(1, "验证码错误.");
		}else{
			String userName = getPara("username");
			String password = ZOMD5.codeFor(getPara("password"));
			MerchUser loginUser = MerchUser.dao.loginFind(userName, password, "2");
			if(loginUser != null){
				if(loginUser.getEnable() == false){
					renderMsg(2, "用户被禁用");
				}else{
					MerchRole role = MerchRole.dao.findById(loginUser.getRoleId());
					if(role == null){
						renderMsg(3, "无角色用户,无法登录");
					}else {
						Merch merch = Merch.dao.selectByMerchCode(loginUser.getMerchCode());
						if(!merch.getIsVerify()){//没有实名
							getSession().setAttribute("loginMerchUser", loginUser);
							renderMsg(4, "请先实名认证");
						}else if(merch.getIsVerify() && !merch.getIsSign()){
							getSession().setAttribute("loginMerchUser", loginUser);
							renderMsg(5, "请先签署合同");
						}
						else {
							getSession().setAttribute("loginMerchUser", loginUser);
							getSession().setAttribute("sidebar", AuthInterceptor.getSidebar_merch_zh_CN());
							setAuthAttr(role);
							renderSuccess();
						}
					}
				}
			}else{
				renderFail("用户名/密码错误");
			}
		}
	}

	private String decode(String bizContent) {
		try {
			bizContent = URLDecoder.decode(bizContent, "utf-8");
			bizContent = new String(Base64.decodeBase64(bizContent.getBytes()));
		} catch (UnsupportedEncodingException e) {
			return "";
		}
		return bizContent;
	}

	public void  cVerify(){//企业
		MerchUser merchUser = (MerchUser) getSession().getAttribute("loginMerchUser");
		Merch merch = Merch.dao.selectByMerchCode(merchUser.getMerchCode());
		Org org = Org.dao.selectByOrgCode(merch.getOrgCode());

		//调用渠道的实名认证: {"code":1,"data":"0703BF1ADC45581D8B2885EFF6008A13","msg":"success"}
		//String res = new FaDadaController().account_register();//先去注册一下

		FddClientBase base = new FddClientBase(FDDConfig.fddappid,FDDConfig.fddapp_secret,fdd_V,fddhost_url);
		String open_id = merch.getCode(); //商户号每一个客户唯一
		String account_type = "2";
		merch.setAccountType(account_type);
		String res =base.invokeregisterAccount(open_id,account_type);
		log.info("FDD -->注册接口返回:" + res);

        String customer_id = null;
        if(res !=null){
            JSONObject json= JSON.parseObject(res);
            String code = json.getString("code");
            if("1".equals(code)){
                customer_id = json.getString("data");
            }
        }
        if(customer_id !=null){
			merch.setCustomerId(customer_id);
			GetCompanyVerifyUrl comverify = new GetCompanyVerifyUrl(APP_ID,APP_SECRET,V,HOST);
			CompanyInfoINO companyInfo = new CompanyInfoINO();
			companyInfo.setCompany_name("");
			companyInfo.setCredit_no("");
			companyInfo.setCredit_image_path("");

			BankInfoINO bankInfo = new BankInfoINO();
			bankInfo.setBank_name("");
			bankInfo.setBank_id("");
			bankInfo.setSubbranch_name("");

			LegalInfoINO legalInfo = new LegalInfoINO();
			legalInfo.setLegal_name("");
			legalInfo.setLegal_id("");
			legalInfo.setLegal_mobile("");
			legalInfo.setLegal_id_front_path("");

			AgentInfoINO agentInfo = new AgentInfoINO();
			agentInfo.setAgent_name("");
			agentInfo.setAgent_id("");
			agentInfo.setAgent_mobile("");
			agentInfo.setAgent_id_front_path("");
			//String customer_id = "";//必填
			/**
			 * 实名认证套餐类型
			 * 0：标准方案（对公打款+纸质审核）默认0；
			 * 1：对公打款；
			 * 2：纸质审核',
			 */
			String verifyed_way = "";
			String page_modify = "1";//必填
			String company_principal_type = "1";//1.法人，2代理人
			String notify_url = FDDConfig.fdd_notify_url_verify;//必填
			String return_url = "";//可填
			String result = comverify.invokeCompanyVerifyUrl(companyInfo,bankInfo,legalInfo
					,agentInfo, customer_id,verifyed_way,page_modify,
					company_principal_type,return_url,notify_url);
			//response.append("\n").append(result);
			log.info("FDD -->获取企业实名接口返回:" + result);
			String data = JSON.parseObject(result).getString("data");
			if (null !=data){
				String url = JSON.parseObject(data).getString("url");
				String transactionNo = JSON.parseObject(data).getString("transactionNo");
				if(transactionNo!=null && transactionNo.length()>0) {
					merch.setTransactionNo(transactionNo);
					url = decode(url);
					System.out.println("FDD---URL--> :" + url);
					merch.update();
					redirect(url);
					return;
				}
			}
        }


		setAttr("merch", merch);
		setAttr("org", org);
		render("console.html");
	}

	public void  pVerify(){//个人
		MerchUser merchUser = (MerchUser) getSession().getAttribute("loginMerchUser");
		Merch merch = Merch.dao.selectByMerchCode(merchUser.getMerchCode());
		Org org = Org.dao.selectByOrgCode(merch.getOrgCode());


		FddClientBase base = new FddClientBase(FDDConfig.fddappid,FDDConfig.fddapp_secret,fdd_V,fddhost_url);
		String open_id = merch.getCode(); //商户号每一个客户唯一
		String account_type = "1";
		merch.setAccountType(account_type);
		String res =base.invokeregisterAccount(open_id,account_type);
		log.info("FDD -->注册接口返回:" + res);

		String customer_id = null;
		if(res !=null){
			JSONObject json= JSON.parseObject(res);
			String code = json.getString("code");
			if("1".equals(code)){
				customer_id = json.getString("data");
			}
		}
		if(customer_id !=null){
			merch.setCustomerId(customer_id);
			GetPersonVerifyUrl personverify = new GetPersonVerifyUrl(APP_ID,APP_SECRET,V,HOST);
			String verifyed_way = "1";
			String page_modify = "2";//是否允许用户页面修改: 1 允许，2 不允许
			String notify_url = FDDConfig.fdd_notify_url_verify;
			String return_url= FDDConfig.fdd_return_url_verify;
			String customer_name = "兰鹏";
			String customer_ident_type = "0";
			String customer_ident_no ="411328198705180010";
			String mobile ="15975508712";
			String ident_front_path ="";
			String result = personverify.invokePersonVerifyUrl(customer_id,verifyed_way,
					page_modify,notify_url,return_url,customer_name,customer_ident_type,
					customer_ident_no,mobile,ident_front_path);

			log.info("FDD -->获取个人实名接口返回:" + result);
			String code = JSON.parseObject(result).getString("code");
			if (!"1".equals(code)){
				renderHtml(result);
				return;
			}
			String data = JSON.parseObject(result).getString("data");
			if (null !=data){
				String url = JSON.parseObject(data).getString("url");
				String transactionNo = JSON.parseObject(data).getString("transactionNo");
				if(transactionNo!=null && transactionNo.length()>0) {
					merch.setTransactionNo(transactionNo);
					url = decode(url);
					System.out.println("FDD---URL--> :" + url);
					merch.update();
					redirect(url);
					return;
				}
			}
		}
		setAttr("merch", merch);
		setAttr("org", org);
		render("console.html");
	}

	public void hetongView(){
		redirect(fdd_hetong_url);
	}

	//签署合同
	public void yesSignNet(){
		MerchUser merchUser = (MerchUser) getSession().getAttribute("loginMerchUser");
		Merch merch = Merch.dao.selectByMerchCode(merchUser.getMerchCode());

		String contract_id = "H" +getSixNum() + ZOIDGenerate.nextOrderNo();//合同编号随机生成
		FddClientBase base = new FddClientBase(APP_ID,APP_SECRET,V,HOST);

		//renderHtml("正在操作网签合同,请稍等...");
		String result = base.invokeUploadDocs(contract_id, "钱包交易合同TEST",
				null, fdd_hetong_url, ".pdf");

		log.info("FDD----合同上传接口返回:" + result);//{"code":"1000","msg":"操作成功","result":"success"}
		if(result!=null){
			String code = JSON.parseObject(result).getString("code");
			if (!"1000".equals(code)){
				renderHtml(result);
				return;
			}
			merch.setContractId(contract_id);


			//调用签署接口
			FddClientBase baseV = new FddClientBase(APP_ID,APP_SECRET,V,HOST);
			ExtsignReq req = new ExtsignReq();
			req.setCustomer_id(merch.getCustomerId());
			req.setTransaction_id("T" +getSixNum() + ZOIDGenerate.nextOrderNo());//签署交易号随机生成);
			merch.setTransactionId(req.getTransaction_id());
			req.setContract_id(contract_id);
			req.setDoc_title("1");
			req.setReturn_url(fdd_return_url_sign);
			String resultV = baseV.invokeExtSign(req);

			log.info("FDD----合同手工签署接口返回:" + resultV);
			if(resultV==null){
				renderHtml("ERROR -1: result == null");
				return;
			}
			merch.update();
			redirect(resultV);
		}else {
			renderHtml("ERROR: result == null");
		}
	}
//合同签署的同步回调
	public void fdd_sign_return(){
		/*
		INFO  - 合同签署同步--->收到FDD同步通知->


JFinal-3.4 action report -------- 2019-02-27 11:51:41 --------------------------
Url         : GET /merch/fdd_sign_return
Controller  : net.gz01.wallet.web.controller.merch.MainController.(MainController.java:1)
Method      : fdd_sign_return
Parameter   : transaction_id=T095222F926569250402443264
timestamp=20190227115141
result_code=3000
msg_digest=MjBERjkxQzZGQTkzQjk4MTNCQUVFNTFEMUVCRTQwQUUxNTE5RjUyRQ==
download_url=https://testapi.fadada.com:8443/api//getdocs.action?app_id=401849&timestamp=20190227115033&v=2.0&msg_digest=NzdBMEQ4NDgyRUQ1QTRGMEZFM0FCNkY2MTdCOTg5MkRGMEZBRjIwNA==&send_app_id=null&transaction_id=T095222F926569250402443264
viewpdf_url=https://testapi.fadada.com:8443/api//viewdocs.action?app_id=401849&timestamp=20190227115033&v=2.0&msg_digest=NzdBMEQ4NDgyRUQ1QTRGMEZFM0FCNkY2MTdCOTg5MkRGMEZBRjIwNA==&send_app_id=null&transaction_id=T095222F926569250402443264
result_desc=签署成功
--------------------------------------------------------------------------------
		 */
		log.info("合同签署同步--->收到FDD同步通知-> \r\n" );
		String transaction_id = getPara("transaction_id");
		String result_code = getPara("result_code");
		String download_url = getPara("download_url");
		String viewpdf_url = getPara("viewpdf_url");
		if("3000".equals(result_code)){
			Merch merch = Merch.dao.findFirst("select * from bd_merch where transaction_id='" +
					transaction_id + "'");
			if(merch!=null && merch.getCode()!=null && !merch.getIsSign()){
				merch.setIsSign(true);
				merch.setDownloadUrl(download_url);
				merch.setViewpdfUrl(viewpdf_url);
				merch.update();

//				//因为这个url是被法大大重定向过来的，所以需要重新保存登录信息到  Session
//				MerchUser merchUser = (MerchUser) getSession().getAttribute("loginMerchUser");
//				if(merchUser==null || merchUser.getMerchCode() == null) {
//					MerchUser loginUser = MerchUser.dao.findFirst("select * from sm_merch_user where merchCode='" +
//							merch.getCode() + "'");
//					log.info("重写登录回话:---->getSession().setAttribute(loginUser);");
//					getSession().setAttribute("loginMerchUser", loginUser);
//					MerchRole role = MerchRole.dao.findById(loginUser.getRoleId());
//
//					getSession().setAttribute("sidebar", AuthInterceptor.getSidebar_merch_zh_CN());
//					setAuthAttr(role);
//				}else {
//					MerchRole role = MerchRole.dao.findById(merchUser.getRoleId());
//					getSession().setAttribute("sidebar", AuthInterceptor.getSidebar_merch_zh_CN());
//					setAuthAttr(role);
//				}
				setAttr("merch", merch);
				render("signSuccess.html");
			}
		}else {
			renderHtml("合同签署失败:" +result_code + ":" + getPara("result_desc") + ",请重新登录签署" );
		}
	}


	//实名认证同步回调, 因为这个url是被法大大重定向过来的，所以需要重新保存登录信息到  Session
	public void fdd_verify_return(){
		String transactionNo = getPara("transactionNo");
		String status = getPara("status");
		String authenticationType = getPara("authenticationType");

		String parameterString = transactionNo + ";" + status + ";" + authenticationType;
		log.info("实名认证--->收到FDD同步通知-> \r\n" + transactionNo);
		int x = 1;
		String sql = "select * from bd_merch where 1=" + x + "" +
				" AND " + "transactionNo='" + transactionNo + "'";
		Merch merch = Merch.dao.findFirst(sql);
		if(merch!=null && merch.getCode()!=null && merch.getAccountType()!=null){
			if(merch.getIsVerify()){

			}else {
				if("1".equals(merch.getAccountType())){//个人实名认证的
					if("2".equals(status)){
						ApplyCert applyCert = new ApplyCert(APP_ID,APP_SECRET,V,HOST);
						String customer_id = merch.getCustomerId();
						String verified_serialno= merch.getTransactionNo();
						String result = applyCert.invokeApplyCert(customer_id,verified_serialno);
						log.info("FDD-->个人实名认证的正式申请返回:" + result);//FDD-->实名认证的正式申请返回:{"code":1,"msg":"success"}
						if("1".equals(JSON.parseObject(result).getString("code"))) {
							merch.setIsVerify(true);
						}
					}
				}
				if("2".equals(merch.getAccountType())){//企业实名认证的
					if("4".equals(status)){
						ApplyCert applyCert = new ApplyCert(APP_ID,APP_SECRET,V,HOST);
						String customer_id = merch.getCustomerId();
						String verified_serialno= merch.getTransactionNo();
						String result = applyCert.invokeApplyCert(customer_id,verified_serialno);
						log.info("FDD-->企业实名认证的正式申请返回:" + result);//FDD-->实名认证的正式申请返回:{"code":1,"msg":"success"}
						if("1".equals(JSON.parseObject(result).getString("code"))) {
							merch.setIsVerify(true);
						}
					}
				}
				merch.update();
			}
		}

		Merch merch1 = Merch.dao.selectByMerchCode(merch.getCode());
		if(merch1.getIsVerify()) {
			//因为这个url是被法大大重定向过来的，所以需要重新保存登录信息到  Session
			MerchUser merchUser = (MerchUser) getSession().getAttribute("loginMerchUser");
			if(merchUser==null || merchUser.getMerchCode() == null) {
				MerchUser loginUser = MerchUser.dao.findFirst("select * from sm_merch_user where merchCode='" +
				merch1.getCode() + "'");
				log.info("重写登录回话:---->getSession().setAttribute(loginUser);");
				getSession().setAttribute("loginMerchUser", loginUser);

			}
			render("signNet.html");
		}else {//实名认证失败
			renderHtml(parameterString);
		}
	}

	/**
	 * 将拥有的权限设置到session供标签使用
	 * @param role
	 */
	private void setAuthAttr(MerchRole role){
		//菜单明细url
		String[] split = role.getSourceUrl().split(",");
		Set<String> menuUrl = new HashSet<>();
		for (String temp : split) {
			menuUrl.add(temp);
		}
		getSession().setAttribute("MERCH" + Authority.MENU_URL, menuUrl);

		//菜单组
		split = role.getSourceGroup().split(",");
		Set<String> menuGroup = new HashSet<>();
		for (String temp : split) {
			menuGroup.add(temp);
		}
		getSession().setAttribute("MERCH" + Authority.MENU_GROUP, menuGroup);

	}

	/**
	 * 获取验证码
	 */
	public void getCaptchaCode(){
		renderCaptcha();
	}


	public void logout(){
		getSession().removeAttribute("loginMerchUser");
		redirect("/merch/loginpage");
	}

}
